package com.ksd.quartz.http;

import com.ksd.quartz.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.Channels;

public class NIOFileDownloader {
    private static Logger logger = LoggerFactory.getLogger(NIOFileDownloader.class);
    public static boolean downloadFile(String fileUrl, String savePath) throws IOException {
        System.out.println("开始进行下载");
        URL url = new URL(fileUrl);
        logger.info("Downloading " + fileUrl);
        logger.info("savePath " + savePath);
        // 获取保存文件的目录
        File saveDir = new File(savePath).getParentFile();
        if (saveDir != null && !saveDir.exists()) {
            // 创建目录
            if (!saveDir.mkdirs()) {
                logger.info("无法创建目录: " + saveDir.getAbsolutePath());
                return false;
            }
        }
        ReadableByteChannel rbc = Channels.newChannel(url.openStream());
        FileOutputStream fos = new FileOutputStream(savePath);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();
        // 检查文件是否存在且大小大于 0
        File downloadedFile = new File(savePath);
        logger.info("下载完成");
        return downloadedFile.exists() && downloadedFile.length() > 0;
    }

    public static void main(String[] args) {
//        String fileUrl = "http://39.106.76.75:9090/update.img";
        ///usr/share/nginx/modules
        String fileUrl = "http://39.106.76.75:9090/poweredby.png";
//        String fileUrl = "http://39.106.76.75:9090/home/admin/api/versionCheckTemp.json";
        String savePath = "D:\\playservice\\云服务器升级数据\\versionCheckTemp.json";// 替换为你希望保存的路径
        try {
            boolean flag = downloadFile(fileUrl, savePath);
            System.out.println("文件是否下载成功:"+flag);
        } catch (IOException e) {
            System.out.println("下载失败: " + e.getMessage());
        }
    }
}